import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "../../api/axios";
import "./Login.css";

const LoginIndex: React.FC = () => {
  const navigate = useNavigate();

  // 手机号验证码登录表单
  const [formData, setFormData] = useState({
    phone: "",
    code: "",
  });

  const [errors, setErrors] = useState({
    phone: "",
    code: "",
  });

  const [isLoading, setIsLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);

  // 表单验证
  const validateForm = () => {
    const newErrors = {
      phone: "",
      code: "",
    };

    if (!formData.phone) {
      newErrors.phone = "请输入手机号";
    } else if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      newErrors.phone = "请输入正确的手机号";
    }

    if (!formData.code) {
      newErrors.code = "请输入验证码";
    } else if (formData.code.length !== 4) {
      newErrors.code = "验证码为4位数字";
    }

    setErrors(newErrors);
    return !Object.values(newErrors).some((error) => error);
  };

  // 处理输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));

    if (errors[name as keyof typeof errors]) {
      setErrors((prev) => ({
        ...prev,
        [name]: "",
      }));
    }
  };

  // 发送验证码
  const handleSendCode = async () => {
    if (!formData.phone) {
      setErrors((prev) => ({ ...prev, phone: "请输入手机号" }));
      return;
    }

    if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      setErrors((prev) => ({ ...prev, phone: "请输入正确的手机号" }));
      return;
    }

    try {
      // 根据API文档，获取验证码使用POST /login，带phone参数
      await axios.post("/login", null, {
        params: { phone: formData.phone },
      });
      alert("验证码已发送");

      // 开始倒计时
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } catch (error) {
      console.error("验证码发送失败:", error);
      alert("验证码发送失败，请检查网络连接或稍后重试");
    }
  };

  // 处理登录
  const handleLogin = async () => {
    if (!validateForm()) {
      return;
    }

    setIsLoading(true);
    try {
      // 根据API文档，判断验证码使用GET /login，带phone参数
      const response = await axios.get("/login", {
        params: {
          phone: formData.phone,
          code: formData.code,
        },
      });

      // 保存登录信息到localStorage
      if (response.data.token) {
        localStorage.setItem("token", response.data.token);
      }
      if (response.data.user) {
        localStorage.setItem("user", JSON.stringify(response.data.user));
      }

      // 显示成功消息
      alert("登录成功！");

      // 跳转到首页
      navigate("/home");
    } catch (error) {
      console.error("登录失败:", error);
      alert("登录失败，请检查验证码");
    } finally {
      setIsLoading(false);
    }
  };

  // 处理回车键登录
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      handleLogin();
    }
  };

  return (
    <div className="login-page">
      <div className="login-container">
        <div className="login-box">
          {/* Logo区域 */}
          <div className="login-header">
            <div className="logo">🏥</div>
            <h1 className="app-title">妙手医生</h1>
            <p className="app-subtitle">互联网医院服务平台</p>
          </div>

          {/* 登录表单 */}
          <div className="login-form">
            <h2 className="login-title">手机号登录</h2>

            {/* 手机号输入 */}
            <div className="form-group">
              <div className="input-wrapper">
                <span className="input-icon">📱</span>
                <input
                  type="tel"
                  name="phone"
                  placeholder="请输入手机号"
                  value={formData.phone}
                  onChange={handleInputChange}
                  onKeyPress={handleKeyPress}
                  className={errors.phone ? "input-error" : ""}
                  disabled={isLoading}
                />
              </div>
              {errors.phone && (
                <div className="error-message">{errors.phone}</div>
              )}
            </div>

            {/* 验证码输入 */}
            <div className="form-group">
              <div className="input-wrapper">
                <span className="input-icon">🔢</span>
                <input
                  type="text"
                  name="code"
                  placeholder="请输入4位验证码"
                  value={formData.code}
                  onChange={handleInputChange}
                  onKeyPress={handleKeyPress}
                  className={errors.code ? "input-error" : ""}
                  disabled={isLoading}
                  maxLength={4}
                />
                <button
                  type="button"
                  className="send-code-btn"
                  onClick={handleSendCode}
                  disabled={isLoading || countdown > 0}
                >
                  {countdown > 0 ? `${countdown}s` : "发送验证码"}
                </button>
              </div>
              {errors.code && (
                <div className="error-message">{errors.code}</div>
              )}
            </div>

            {/* 登录按钮 */}
            <button
              className={`login-button ${isLoading ? "loading" : ""}`}
              onClick={handleLogin}
              disabled={isLoading}
            >
              {isLoading ? (
                <>
                  <span className="loading-spinner"></span>
                  登录中...
                </>
              ) : (
                "登录"
              )}
            </button>

            {/* 其他登录方式 */}
            <div className="other-login">
              <div className="divider">
                <span>其他登录方式</span>
              </div>
              <div className="social-login">
                <button className="social-btn wechat" disabled={isLoading}>
                  💬 微信登录
                </button>
              </div>
            </div>

            {/* 注册链接 */}
            <div className="register-link">
              还没有账号？
              <button type="button" disabled={isLoading}>
                立即注册
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default LoginIndex;
